import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
//        List<List<Integer>> res = solution.fourSum(new int[]{2,2,2,2,2}, 8);
        List<List<Integer>> res = solution.fourSum(new int[]{1,0,-1,0,-2,2}, 0);
//        List<List<Integer>> res = solution.fourSum(new int[]{-1,-1,-1,-1,0,0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4}, 3);
        System.out.println(res);
    }
}

//注意：溢出问题，中间结果使用long类型
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);

        List<List<Integer>> res = new ArrayList<>();
        for(int i = 0; i < nums.length - 3; i++){
            if(i > 0 && nums[i] == nums[i - 1]) continue;
            if((long)nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) break;
            for(int j = i + 1; j < nums.length - 2; j++){
                if(j > i + 1 && nums[j] == nums[j - 1]) continue;
                if((long)nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) break;
                int l = nums.length - 1;
                for(int k = j + 1; k < nums.length - 1; k++){
                    if(k > j + 1 && nums[k] == nums[k - 1]) continue;

                    int a = nums[i];
                    int b = nums[j];
                    int c = nums[k];
                    long expectedD = (long)target - a - b - c;

                    while(l > k && nums[l] > expectedD) l--;
                    if(l <= k){
                        break;
                    }
                    if(nums[l] == expectedD){
                        res.add(Arrays.asList(a, b, c, (int)expectedD));
//                        l--;
                    }
                }
            }
        }
        return res;
    }
}